'use strict';
const db = uniCloud.database()
const usersCollection = db.collection('users')
const smsCodeCollection = db.collection('sms_codes')

exports.main = async (event, context) => {
	const { phone, type } = event
	
	// 验证手机号格式
	const phoneReg = /^1[3-9]\d{9}$/
	if (!phoneReg.test(phone)) {
		return {
			code: -1,
			msg: '手机号格式不正确'
		}
	}
	
	try {
		// 检查手机号是否已注册
		if (type === 'register') {
			const user = await usersCollection.where({
				phone: phone
			}).get()
			
			if (user.data.length > 0) {
				return {
					code: -1,
					msg: '该手机号已注册'
				}
			}
		}
		
		// 生成6位随机验证码
		const code = Math.random().toString().slice(-6)
		
		// 保存验证码到数据库
		await smsCodeCollection.add({
			phone,
			code,
			type,
			createTime: Date.now(),
			expireTime: Date.now() + 5 * 60 * 1000 // 5分钟有效期
		})
		
		// TODO: 调用短信服务发送验证码
		// 这里需要接入实际的短信服务
		
		return {
			code: 0,
			msg: '验证码已发送'
		}
	} catch (e) {
		return {
			code: -1,
			msg: '发送失败',
			error: e
		}
	}
}; 